package edu.sctu.jsoup.service;

import edu.sctu.jsoup.entity.ChinaCityEntity;
import edu.sctu.jsoup.entity.CityNameEntity;
import edu.sctu.jsoup.repo.ChinaCityRepo;
import edu.sctu.jsoup.repo.CityNameRepo;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.List;

/**
 * Created by Administrator on 2017/12/10.
 */
@Service
public class CityNameService {

    @Autowired
    private ChinaCityRepo chinaCityRepo;

    @Autowired
    private CityNameRepo cityNameRepo;

    public void run() throws IOException {
        List<ChinaCityEntity> chinaCityEntities = chinaCityRepo.findAll();
          for (int k = 0; k < chinaCityEntities.size(); k++) {
              if (k<87) continue;
            String kk= chinaCityEntities.get(k).getCode();
            String temp = "";

              lable: for (int j = 0; ; j++) {

                  if (j%10==0&&j!=0) try {
                      System.out.println("=======休息5秒钟===========");
                      Thread.sleep(5000);
                  } catch (InterruptedException e) {
                      e.printStackTrace();
                  }


                  Document document = Jsoup.connect("https://www.tripadvisor.cn/TourismChildrenAjax?geo="+kk+"&offset=" + j).get();
                Elements elements = document.select("a");
                if (temp.equals(elements.get(0).text().substring(elements.get(0).text().indexOf(" ")))) break lable;
                for (int i = 0; i < elements.size(); i++) {
                    CityNameEntity cityNameEntity=new CityNameEntity();
                    cityNameEntity.setCode(chinaCityEntities.get(k).getCode());
                    cityNameEntity.setCountryName(chinaCityEntities.get(k).getName());
                    cityNameEntity.setCityName(elements.get(i).text());
                    cityNameRepo.save(cityNameEntity);
                    if (i == 0) temp = elements.get(0).text().substring(elements.get(0).text().indexOf(" "));
                }
            }
        }


//        Document document= Jsoup.connect("https://www.tripadvisor.cn/Lvyou").get();
//        Element element=document.select("#PAGE").first();
//        Elements EE=element.select("#MAINWRAP");
//        Elements EE1=EE.select(".sizedThumb");
//        System.out.println(EE1);
//        Elements EE2=EE1.select("a");
//        System.out.println(EE2);
//        Elements EE3=EE2.select("span[class=name]");
//
//
//        System.out.println(EE3.text());


//        for (int j=0;;j++) {
//            Document document = Jsoup.connect("https://www.tripadvisor.cn/TourismChildrenAjax?geo=294211&offset="+j).get();
//            Elements ee = document.select("a");
//            for (int i = 0; i < ee.size(); i++) {
//                System.out.println(ee.get(i).text());
//            }
//        }


    }
}
